<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>Kotlin编程第一课--(协程篇)24  实战：让KtHttp支持Flow | 码行</title><meta name="author" content="Carl Su"><meta name="copyright" content="Carl Su"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="Kotlin编程第一课–(协程篇)24 | 实战：让KtHttp支持Flow又到了熟悉的实战环节，这一次我们接着来改造 KtHttp，让它能够支持协程的 Flow API。 有了前面两次实战的基础，这次我们应该就轻车熟路了。在之前的4.0 版本中，为了让 KtHttp 支持挂起函数，我们有两种思路，一种是改造内部，另一种是扩展外部。同理，为了让 KtHttp 支持 Flow，这次的实战也是这两种思">
<meta property="og:type" content="article">
<meta property="og:title" content="Kotlin编程第一课--(协程篇)24  实战：让KtHttp支持Flow">
<meta property="og:url" content="https://devsu.top/posts/6532289/index.html">
<meta property="og:site_name" content="码行">
<meta property="og:description" content="Kotlin编程第一课–(协程篇)24 | 实战：让KtHttp支持Flow又到了熟悉的实战环节，这一次我们接着来改造 KtHttp，让它能够支持协程的 Flow API。 有了前面两次实战的基础，这次我们应该就轻车熟路了。在之前的4.0 版本中，为了让 KtHttp 支持挂起函数，我们有两种思路，一种是改造内部，另一种是扩展外部。同理，为了让 KtHttp 支持 Flow，这次的实战也是这两种思">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://t15.baidu.com/it/u=1016075162,2061563941&fm=224&app=112&f=JPEG?w=354&h=500">
<meta property="article:published_time" content="2022-06-04T07:04:50.000Z">
<meta property="article:modified_time" content="2023-03-23T07:58:56.021Z">
<meta property="article:author" content="Carl Su">
<meta property="article:tag" content="Kotlin">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://t15.baidu.com/it/u=1016075162,2061563941&fm=224&app=112&f=JPEG?w=354&h=500"><link rel="shortcut icon" href="https://s2.loli.net/2023/03/09/whMHdYkrKoIBnSC.png"><link rel="canonical" href="https://devsu.top/posts/6532289/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?6243425e2ecb037931274c4ca1db3132";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":300},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Carl Su","link":"链接: ","source":"来源: 码行","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Kotlin编程第一课--(协程篇)24  实战：让KtHttp支持Flow',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-03-23 15:58:56'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://s2.loli.net/2023/03/09/QrI9mgJ4XlbEPzN.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">169</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">37</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">38</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg fixed" id="page-header" style="background-image: url('http://t15.baidu.com/it/u=1016075162,2061563941&amp;fm=224&amp;app=112&amp;f=JPEG?w=354&amp;h=500')"><nav id="nav"><span id="blog-info"><a href="/" title="码行"><img class="site-icon" src="https://s2.loli.net/2023/03/09/whMHdYkrKoIBnSC.png"/><span class="site-name">码行</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Kotlin编程第一课--(协程篇)24  实战：让KtHttp支持Flow</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-06-04T07:04:50.000Z" title="发表于 2022-06-04 15:04:50">2022-06-04</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-03-23T07:58:56.021Z" title="更新于 2023-03-23 15:58:56">2023-03-23</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/">Android</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/Kotlin/">Kotlin</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/Kotlin/Kotlin%E7%BC%96%E7%A8%8B%E7%AC%AC%E4%B8%80%E8%AF%BE/">Kotlin编程第一课</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">5.5k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>22分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Kotlin编程第一课--(协程篇)24  实战：让KtHttp支持Flow"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Kotlin编程第一课–-协程篇-24-实战：让KtHttp支持Flow"><a href="#Kotlin编程第一课–-协程篇-24-实战：让KtHttp支持Flow" class="headerlink" title="Kotlin编程第一课–(协程篇)24 | 实战：让KtHttp支持Flow"></a>Kotlin编程第一课–(协程篇)24 | 实战：让KtHttp支持Flow</h1><p>又到了熟悉的实战环节，这一次我们接着来改造 KtHttp，让它能够支持协程的 Flow API。</p>
<p>有了前面两次实战的基础，这次我们应该就轻车熟路了。在之前的4.0 版本中，为了让 KtHttp 支持挂起函数，我们有两种思路，一种是<strong>改造内部</strong>，另一种是扩展外部。同理，为了让 KtHttp 支持 Flow，这次的实战也是这两种思路。</p>
<p>因此，这节课我们仍然会分为两个版本。</p>
<ul>
<li><p>5.0 版本，基于 4.0 版本的代码，从 KtHttp 的<strong>外部扩展</strong>出 Flow 的能力。</p>
</li>
<li><p>6.0 版本，<strong>修改 KtHttp 内部</strong>，让它支持 Flow API。</p>
</li>
</ul>
<p>其实在实际的工作中，我们往往没有权限修改第三方提供的 SDK，那么这时候，如果想要让 SDK 获得 Flow 的能力，我们就只能借助 Kotlin 的扩展函数，为它<strong>扩展</strong>出 Flow 的能力。而对于工程内部的代码，我们希望某个功能模块获得 Flow 的能力，就可以<strong>直接修改它的源代码</strong>，让它直接支持 Flow。</p>
<p>那么在这节课里，我会同时用这两种手段来扩展并改造 KtHttp，为你演示其中的关键步骤。在这个过程中，我也会为你讲解其中的常见误区和陷阱，这样一来，你就可以放心地将 Flow 应用到你的实际工作中了。</p>
<p>OK，让我们正式开始吧！</p>
<h2 id="5-0-版本：Callback-转-Flow"><a href="#5-0-版本：Callback-转-Flow" class="headerlink" title="5.0 版本：Callback 转 Flow"></a>5.0 版本：Callback 转 Flow</h2><p>在上次的实战课当中，我们在 3.0 版本里，实现了 KtHttp 的异步 Callback 请求。之后在 4.0 版本里，我们并没有改动 KtHttp 的源代码，而是直接在 KtCall 的基础上扩展了<strong>挂起函数</strong>的支持。让我们重新回顾一下之前的代码：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段1</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 扩展函数</span></span><br><span class="line"><span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="type">&lt;T : Any&gt;</span> KtCall<span class="type">&lt;T&gt;</span>.<span class="title">await</span><span class="params">()</span></span>: T =</span><br><span class="line"><span class="comment">//      暴露挂起函数的continuation</span></span><br><span class="line"><span class="comment">//              ↓</span></span><br><span class="line">    suspendCancellableCoroutine &#123; continuation -&gt;</span><br><span class="line">        <span class="keyword">val</span> call = call(<span class="keyword">object</span> : Callback&lt;T&gt; &#123;</span><br><span class="line">            <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onSuccess</span><span class="params">(<span class="keyword">data</span>: <span class="type">T</span>)</span></span> &#123;</span><br><span class="line">                println(<span class="string">&quot;Request success!&quot;</span>)</span><br><span class="line">                continuation.resume(<span class="keyword">data</span>)</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onFail</span><span class="params">(throwable: <span class="type">Throwable</span>)</span></span> &#123;</span><br><span class="line">                println(<span class="string">&quot;Request fail!：<span class="variable">$throwable</span>&quot;</span>)</span><br><span class="line">                continuation.resumeWithException(throwable)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">//          响应取消事件</span></span><br><span class="line"><span class="comment">//              ↓</span></span><br><span class="line">        continuation.invokeOnCancellation &#123;</span><br><span class="line">            println(<span class="string">&quot;Call cancelled!&quot;</span>)</span><br><span class="line">            call.cancel()</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>我们知道，上面这种做法非常适合针对第三方 SDK 的扩展，而这一切，都要归功于 Kotlin 的<strong>扩展函数</strong>特性。那么这节课里，我们希望 KtHttp 支持 Flow，其实也同样可以借助扩展函数来实现。Kotlin 官方提供了一个 API：<strong>callbackFlow</strong>，它就是专门用于将 Callback 转为 Flow 的。</p>
<p>Callback 转 Flow，用法跟 Callback 转挂起函数是差不多的。如果你去分析代码段 1 当中的代码模式，会发现 Callback 转挂起函数，主要有三个步骤。</p>
<ul>
<li>第一步：使用 suspendCancellableCoroutine 执行 Callback 代码，等待 Callback 回调；</li>
<li>第二步：将 Callback 回调结果传出去，onSuccess 的情况就传结果，onFail 的情况就传异常；</li>
<li>第三步：响应协程取消事件 invokeOnCancellation{}。</li>
</ul>
<p>所以使用 callbackFlow，也是这样三个步骤。如果你看过 Google 官方写的文档，你可能会写出这样的代码：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段2</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="type">&lt;T : Any&gt;</span> KtCall<span class="type">&lt;T&gt;</span>.<span class="title">asFlow</span><span class="params">()</span></span>: Flow&lt;T&gt; = callbackFlow &#123;</span><br><span class="line">    <span class="comment">// 调用Callback</span></span><br><span class="line">    <span class="keyword">val</span> call = call(<span class="keyword">object</span> : Callback&lt;T&gt; &#123;</span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onSuccess</span><span class="params">(<span class="keyword">data</span>: <span class="type">T</span>)</span></span> &#123;</span><br><span class="line">            <span class="comment">// 1，传递成功数据，报错！</span></span><br><span class="line">            offer(<span class="keyword">data</span>)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onFail</span><span class="params">(throwable: <span class="type">Throwable</span>)</span></span> &#123;</span><br><span class="line">            <span class="comment">// 2，传递失败数据</span></span><br><span class="line">            close(throwable)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 3，响应协程取消</span></span><br><span class="line">    awaitClose &#123;</span><br><span class="line">        call.cancel()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在这段代码里，callbackFlow 的使用步骤也是分了三步。不过，由于 Google 官方写的文档已经有些过时了，如果你按照文档来写，会发现注释 1 处的代码其实会报错，IDE 会提示应该使用 trySend() 替代 offer()。</p>
<p>所以我们要再来改一改：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段3</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="type">&lt;T : Any&gt;</span> KtCall<span class="type">&lt;T&gt;</span>.<span class="title">asFlow</span><span class="params">()</span></span>: Flow&lt;T&gt; = callbackFlow &#123;</span><br><span class="line">    <span class="keyword">val</span> call = call(<span class="keyword">object</span> : Callback&lt;T&gt; &#123;</span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onSuccess</span><span class="params">(<span class="keyword">data</span>: <span class="type">T</span>)</span></span> &#123;</span><br><span class="line">            <span class="comment">// 1</span></span><br><span class="line">            trySend(<span class="keyword">data</span>)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onFail</span><span class="params">(throwable: <span class="type">Throwable</span>)</span></span> &#123;</span><br><span class="line">            <span class="comment">// 2</span></span><br><span class="line">            close(throwable)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;)</span><br><span class="line"></span><br><span class="line">    awaitClose &#123;</span><br><span class="line">        call.cancel()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>那么从上面的代码中，你会发现，callbackFlow 的底层用到了 Channel，所以你才可以使用 trySend() 这样的 API。这个 API 我在第 19 讲里提到过，它其实就是 Channel.send() 的<strong>非挂起函数</strong>版本的 API。这样改完以后，我们的代码就已经没有明显报错了。</p>
<p>但，它仍然还有优化空间，对应的地方我已经用注释标记出来了。</p>
<p>我们来看一下注释 1，这里使用 trySend()，虽然在这个案例当中用这个 API 确实没问题，但在大部分场景下，它其实是不够稳妥的。你可以查看一下它的源码文档，会看到它的返回值类型是 <strong>ChannelResult</strong>，代表 trySend() 的执行结果是成功还是失败。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段4</span></span><br><span class="line"><span class="keyword">public</span> <span class="function"><span class="keyword">fun</span> <span class="title">trySend</span><span class="params">(element: <span class="type">E</span>)</span></span>: ChannelResult&lt;<span class="built_in">Unit</span>&gt;</span><br></pre></td></tr></table></figure>

<p>也就是说，如果我们往 Channel 当中成功地添加了元素，那么 trySend() 的返回值就是成功，如果当前的 Channel 管道已经满了，那么 trySend() 的返回值就是失败。</p>
<p>其实，当 Channel 管道容量已满的时候，我们更希望 trySend() 可以多等等，直到管道容量空闲以后再返回成功。所以这时候，我们可以使用 <strong>trySendBlocking()</strong> 来替代它。它是 Kotlin 协程 1.5 出现的一个新的 API。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段5</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="type">&lt;T : Any&gt;</span> KtCall<span class="type">&lt;T&gt;</span>.<span class="title">asFlow</span><span class="params">()</span></span>: Flow&lt;T&gt; = callbackFlow &#123;</span><br><span class="line">    <span class="keyword">val</span> call = call(<span class="keyword">object</span> : Callback&lt;T&gt; &#123;</span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onSuccess</span><span class="params">(<span class="keyword">data</span>: <span class="type">T</span>)</span></span> &#123;</span><br><span class="line">            <span class="comment">// 1，变化在这里</span></span><br><span class="line">            trySendBlocking(<span class="keyword">data</span>)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onFail</span><span class="params">(throwable: <span class="type">Throwable</span>)</span></span> &#123;</span><br><span class="line">            <span class="comment">// 2</span></span><br><span class="line">            close(throwable)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;)</span><br><span class="line"></span><br><span class="line">    awaitClose &#123;</span><br><span class="line">        call.cancel()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>不过，这里我们仅仅只是改为 trySendBlocking() 仍然还不够，让我们来运行一下程序，看看问题出在哪里：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段6</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> <span class="title class_">ApiServiceV5</span> &#123;</span><br><span class="line">    <span class="meta">@GET(<span class="string">&quot;/repo&quot;</span>)</span></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">repos</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">        <span class="meta">@Field(<span class="string">&quot;lang&quot;</span>)</span> lang: <span class="type">String</span>,</span></span></span><br><span class="line"><span class="params"><span class="function">        <span class="meta">@Field(<span class="string">&quot;since&quot;</span>)</span> since: <span class="type">String</span></span></span></span><br><span class="line"><span class="params"><span class="function">    )</span></span>: KtCall&lt;RepoList&gt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    testFlow()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">testFlow</span><span class="params">()</span></span> =</span><br><span class="line">    KtHttpV5.create(ApiServiceV5::<span class="keyword">class</span>.java)</span><br><span class="line">        .repos(lang = <span class="string">&quot;Kotlin&quot;</span>, since = <span class="string">&quot;weekly&quot;</span>)</span><br><span class="line">        .asFlow()</span><br><span class="line">        .<span class="keyword">catch</span> &#123; println(<span class="string">&quot;Catch: <span class="variable">$it</span>&quot;</span>) &#125;</span><br><span class="line">        .collect &#123;</span><br><span class="line">        println(it)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出正常</span></span><br><span class="line"><span class="comment">程序不会终止</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>其实，问题的原因也很简单，由于 callbackFlow 的底层是 Channel 实现的，在我们用完它以后，应该主动将其关闭或者释放。不然的话，它就会一直<strong>占用计算机资源</strong>。所以这时候，我们可以进一步完善 trySendBlocking() 这部分的代码。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段7</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="type">&lt;T : Any&gt;</span> KtCall<span class="type">&lt;T&gt;</span>.<span class="title">asFlow</span><span class="params">()</span></span>: Flow&lt;T&gt; = callbackFlow &#123;</span><br><span class="line">    <span class="keyword">val</span> call = call(<span class="keyword">object</span> : Callback&lt;T&gt; &#123;</span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onSuccess</span><span class="params">(<span class="keyword">data</span>: <span class="type">T</span>)</span></span> &#123;</span><br><span class="line">            <span class="comment">// 1，变化在这里</span></span><br><span class="line">            trySendBlocking(<span class="keyword">data</span>)</span><br><span class="line">                .onSuccess &#123; close() &#125;</span><br><span class="line">                .onFailure &#123; close(it) &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onFail</span><span class="params">(throwable: <span class="type">Throwable</span>)</span></span> &#123;</span><br><span class="line">            close(throwable)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;)</span><br><span class="line"></span><br><span class="line">    awaitClose &#123;</span><br><span class="line">        call.cancel()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">输出正常</span></span><br><span class="line"><span class="comment">程序等待一会后自动终止</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>上面代码中的 onSuccess、onFailure 其实就相当于回调，在这里，不管是成功还是失败，我们都主动把 callbackFlow 当中的 Channel 关闭。这样一来，程序就可以正常终止了。</p>
<p><code>提示：在大部分场景下 trySendBlocking() 会比 trySend() 更稳妥一些，因为它会尽可能发送成功。但在某些特殊情况下，trySend() 也有它的优势，因为它不会出现阻塞问题。</code></p>
<p>好，现在，5.0 版本的代码其实就已经算是合格了。不过，我还想给你介绍下 callbackFlow 的一些使用细节：**close() 与 close(throwable)**。</p>
<p>close() 这个方法，我们既可以传入异常，也可以不传入。不过，这两者在 callbackFlow 当中是有差异的。如果你将代码段 7 当中所有的 close(throwable) 都改为不传异常的话，程序代码也会出现问题。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段8</span></span><br><span class="line"><span class="comment">// 错误示范！错误示范！错误示范！</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    testFlow()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">testFlow</span><span class="params">()</span></span> =</span><br><span class="line">    KtHttpV5.create(ApiServiceV5::<span class="keyword">class</span>.java)</span><br><span class="line">        .repos(lang = <span class="string">&quot;Kotlin&quot;</span>, since = <span class="string">&quot;weekly&quot;</span>)</span><br><span class="line">        .asFlow()</span><br><span class="line">        .<span class="keyword">catch</span> &#123; println(<span class="string">&quot;Catch: <span class="variable">$it</span>&quot;</span>) &#125;</span><br><span class="line">        .collect &#123;</span><br><span class="line">            println(it)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="type">&lt;T : Any&gt;</span> KtCall<span class="type">&lt;T&gt;</span>.<span class="title">asFlow</span><span class="params">()</span></span>: Flow&lt;T&gt; = callbackFlow &#123;</span><br><span class="line">    <span class="keyword">val</span> call = call(<span class="keyword">object</span> : Callback&lt;T&gt; &#123;</span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onSuccess</span><span class="params">(<span class="keyword">data</span>: <span class="type">T</span>)</span></span> &#123;</span><br><span class="line">            trySendBlocking(<span class="keyword">data</span>)</span><br><span class="line">                .onSuccess &#123; close() &#125;</span><br><span class="line">                .onFailure &#123;</span><br><span class="line">                    <span class="comment">// 变化在这里</span></span><br><span class="line">                    close()</span><br><span class="line">                &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onFail</span><span class="params">(throwable: <span class="type">Throwable</span>)</span></span> &#123;</span><br><span class="line">            <span class="comment">// 变化在这里</span></span><br><span class="line">            close()</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line"></span><br><span class="line">    awaitClose &#123;</span><br><span class="line">        call.cancel()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">断网执行以上代码：</span></span><br><span class="line"><span class="comment">不会有任何结果，连异常信息都没有</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>在以上代码中，我们断网执行了这段程序，但在控制台上看不到任何异常的输出信息。这就是因为，我们调用 close() 的时候没有传入异常信息。</p>
<p>所以，在 callbackFlow 当中的异常分支里，我们如果使用 close()，一定要<strong>带上对应的异常</strong>，就像代码段 7 的那样“close(throwable)”。或者，为了防止在开发的过程中忘记传入异常信息，我们可以使用 <strong>cancel() 方法</strong>。就像下面这样：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段9</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="type">&lt;T : Any&gt;</span> KtCall<span class="type">&lt;T&gt;</span>.<span class="title">asFlow</span><span class="params">()</span></span>: Flow&lt;T&gt; = callbackFlow &#123;</span><br><span class="line">    <span class="keyword">val</span> call = call(<span class="keyword">object</span> : Callback&lt;T&gt; &#123;</span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onSuccess</span><span class="params">(<span class="keyword">data</span>: <span class="type">T</span>)</span></span> &#123;</span><br><span class="line">            trySendBlocking(<span class="keyword">data</span>)</span><br><span class="line">                .onSuccess &#123; close() &#125;</span><br><span class="line">                .onFailure &#123;</span><br><span class="line">                    <span class="comment">// 变化在这里</span></span><br><span class="line">                    cancel(CancellationException(<span class="string">&quot;Send channel fail!&quot;</span>, it))</span><br><span class="line">                &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onFail</span><span class="params">(throwable: <span class="type">Throwable</span>)</span></span> &#123;</span><br><span class="line">            <span class="comment">// 变化在这里</span></span><br><span class="line">            cancel(CancellationException(<span class="string">&quot;Request fail!&quot;</span>, throwable))</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line"></span><br><span class="line">    awaitClose &#123;</span><br><span class="line">        call.cancel()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">断网执行</span></span><br><span class="line"><span class="comment">Catch: java.util.concurrent.CancellationException: Request fail!</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>根据这里的运行结果，我们可以看到，把 close() 改成 cancel() 以后，程序运行结果也符合预期。而 cancel 其实还有一个优势：就算不小心忘记传 throwable，我们还是可以看到一个 CancellationException。</p>
<p>不过总的来说，只要我们可以记住传入异常信息，close() 和 cancel() 两者的差别并不大。</p>
<p>另外还有一点，如果我们在 callbackFlow 当中还启动了其他的协程任务，close() 和 cancel() 也同样可以取消对应的协程。如下所示：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段10</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    testFlow()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">testFlow</span><span class="params">()</span></span> =</span><br><span class="line">    KtHttpV5.create(ApiServiceV5::<span class="keyword">class</span>.java)</span><br><span class="line">        .repos(lang = <span class="string">&quot;Kotlin&quot;</span>, since = <span class="string">&quot;weekly&quot;</span>)</span><br><span class="line">        .asFlow() <span class="comment">// 注意这里</span></span><br><span class="line">        .<span class="keyword">catch</span> &#123; println(<span class="string">&quot;Catch: <span class="variable">$it</span>&quot;</span>) &#125;</span><br><span class="line">        .collect &#123;</span><br><span class="line">        println(it)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="type">&lt;T : Any&gt;</span> KtCall<span class="type">&lt;T&gt;</span>.<span class="title">asFlow</span><span class="params">()</span></span>: Flow&lt;T&gt; = callbackFlow &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> job = launch &#123;</span><br><span class="line">        println(<span class="string">&quot;Coroutine start&quot;</span>)</span><br><span class="line">        delay(<span class="number">3000L</span>)</span><br><span class="line">        println(<span class="string">&quot;Coroutine end&quot;</span>) <span class="comment">// 没有机会执行</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    job.invokeOnCompletion &#123;</span><br><span class="line">        println(<span class="string">&quot;Coroutine completed <span class="variable">$it</span>&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">val</span> call = call(<span class="keyword">object</span> : Callback&lt;T&gt; &#123;</span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onSuccess</span><span class="params">(<span class="keyword">data</span>: <span class="type">T</span>)</span></span> &#123;</span><br><span class="line">            trySendBlocking(<span class="keyword">data</span>)</span><br><span class="line">                .onSuccess &#123; close() &#125;</span><br><span class="line">                .onFailure &#123;</span><br><span class="line">                    cancel(CancellationException(<span class="string">&quot;Send channel fail!&quot;</span>, it))</span><br><span class="line">                &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onFail</span><span class="params">(throwable: <span class="type">Throwable</span>)</span></span> &#123;</span><br><span class="line">            cancel(CancellationException(<span class="string">&quot;Request fail!&quot;</span>, throwable))</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line"></span><br><span class="line">    awaitClose &#123;</span><br><span class="line">        call.cancel()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">断网执行</span></span><br><span class="line"><span class="comment">Coroutine start</span></span><br><span class="line"><span class="comment">Coroutine completed java.util.concurrent.CancellationException: Request fail!</span></span><br><span class="line"><span class="comment">Catch: java.util.concurrent.CancellationException: Request fail!</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>可以看到，由于协程是结构化的，所以，当我们取消 callbackFlow 的时候，在它内部创建的协程 job，也会跟着被取消。而且，它的异常信息也是一样的。</p>
<p>不过，如果我们把上面的 launch{} 改成了“launch(Job()){}”，那么，协程任务就不会跟随 callbackFlow 一起被取消了。我相信，如果你还记得上节课讲的第二条准则，那你一定可以轻松理解这句话。因为，它们的协程的父子关系已经被破坏了！</p>
<p>最后，我还想再提一下 awaitClose{} 这个挂起函数，它的作用其实就是监听 callbackFlow 的生命周期，当它被关闭或者取消的时候，我们应该同时把 OkHttp 当中的网络请求也取消掉。它的作用，跟代码段 1 当中的 continuation.invokeOnCancellation{} 是类似的。</p>
<p>好，callbackFlow 的用法我们就讲解完了，有了它，以后我们就可以轻松地把第三方 SDK 的 Callback 扩展成 Flow 了。</p>
<p>那么接下来，我们就进入 6.0 版本的开发吧！</p>
<h2 id="6-0-版本：直接支持-Flow"><a href="#6-0-版本：直接支持-Flow" class="headerlink" title="6.0 版本：直接支持 Flow"></a>6.0 版本：直接支持 Flow</h2><p>实际上，对于 KtHttp 来说，4.0 版本、5.0 版本都只是外部扩展，我们对 KtHttp 的内部源代码并没有做改动。</p>
<p>而对于 6.0 版本的开发，我们其实是希望 KtHttp 可以直接支持返回 Flow 类型的数据，也就是这样：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段11</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> <span class="title class_">ApiServiceV5</span> &#123;</span><br><span class="line">    <span class="meta">@GET(<span class="string">&quot;/repo&quot;</span>)</span></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">repos</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">        <span class="meta">@Field(<span class="string">&quot;lang&quot;</span>)</span> lang: <span class="type">String</span>,</span></span></span><br><span class="line"><span class="params"><span class="function">        <span class="meta">@Field(<span class="string">&quot;since&quot;</span>)</span> since: <span class="type">String</span></span></span></span><br><span class="line"><span class="params"><span class="function">    )</span></span>: KtCall&lt;RepoList&gt;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GET(<span class="string">&quot;/repo&quot;</span>)</span></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">reposFlow</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">        <span class="meta">@Field(<span class="string">&quot;lang&quot;</span>)</span> lang: <span class="type">String</span>,</span></span></span><br><span class="line"><span class="params"><span class="function">        <span class="meta">@Field(<span class="string">&quot;since&quot;</span>)</span> since: <span class="type">String</span></span></span></span><br><span class="line"><span class="params"><span class="function">    )</span></span>: Flow&lt;RepoList&gt; <span class="comment">// 注意这里</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>请你留意上面的代码注释，在 ApiServiceV5 当中，我定义了一个接口方法 reposFlow()，它的返回值类型是 Flow，而不是之前的 KtCall。这样一来，我们在 main() 函数当中使用它的时候，就不需要使用 asFlow() 这个扩展函数了。就像下面这样：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段12</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">testFlow</span><span class="params">()</span></span> =</span><br><span class="line">    KtHttpV5.create(ApiServiceV5::<span class="keyword">class</span>.java)</span><br><span class="line">        .reposFlow(lang = <span class="string">&quot;Kotlin&quot;</span>, since = <span class="string">&quot;weekly&quot;</span>)</span><br><span class="line">        <span class="comment">// 注意这里不需要asFlow，因为reposFlow()返回值类型就是Flow</span></span><br><span class="line">        .<span class="keyword">catch</span> &#123; println(<span class="string">&quot;Catch: <span class="variable">$it</span>&quot;</span>) &#125;</span><br><span class="line">        .collect &#123;</span><br><span class="line">            println(it)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    testFlow()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到，当我们把 reposFlow() 的返回值类型定义成 Flow 以后，就需要改动 KtHttp 的源代码了。因为，它的内部需要根据这种情况做一些特殊的判断。</p>
<p>其实，在前面 3.0 版本的开发中，我们就已经做过一次判断了。当时，我们特地判断了一下，返回值类型是 KtCall 还是T。让我们来重新回顾一下当时的代码细节：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段13</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="type">&lt;T: Any&gt;</span> <span class="title">invoke</span><span class="params">(path: <span class="type">String</span>, method: <span class="type">Method</span>, args: <span class="type">Array</span>&lt;<span class="type">Any</span>&gt;)</span></span>: Any? &#123;</span><br><span class="line">    <span class="comment">// 省略部分代码</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">if</span> (isKtCallReturn(method)) &#123;</span><br><span class="line">        <span class="comment">// 返回值类型是KtCall&lt;RepoList&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">val</span> genericReturnType = getTypeArgument(method)</span><br><span class="line">        KtCall&lt;T&gt;(call, gson, genericReturnType)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 返回值类型是 RepoList</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">val</span> response = okHttpClient.newCall(request).execute()</span><br><span class="line">        <span class="keyword">val</span> genericReturnType = method.genericReturnType</span><br><span class="line">        <span class="keyword">val</span> json = response.body?.string()</span><br><span class="line">        gson.fromJson&lt;Any?&gt;(json, genericReturnType)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>看到上面的代码，相信你马上就能想明白了，如果要支持 Flow，我们只需要在这里判断一下，返回值类型是不是 Flow 即可。比如说：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段14</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="type">&lt;T : Any&gt;</span> <span class="title">invoke</span><span class="params">(path: <span class="type">String</span>, method: <span class="type">Method</span>, args: <span class="type">Array</span>&lt;<span class="type">Any</span>&gt;)</span></span>: Any? &#123;</span><br><span class="line">    <span class="comment">// 省略部分代码</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">when</span> &#123;</span><br><span class="line">        isKtCallReturn(method) -&gt; &#123;</span><br><span class="line">            <span class="keyword">val</span> genericReturnType = getTypeArgument(method)</span><br><span class="line">            KtCall&lt;T&gt;(call, gson, genericReturnType)</span><br><span class="line">        &#125;</span><br><span class="line">        isFlowReturn(method) -&gt; &#123;</span><br><span class="line">            <span class="comment">// 直接返回Flow</span></span><br><span class="line">            flow&lt;T&gt; &#123;</span><br><span class="line">                <span class="comment">// 请求API</span></span><br><span class="line">                <span class="keyword">val</span> genericReturnType = getTypeArgument(method)</span><br><span class="line">                <span class="keyword">val</span> response = okHttpClient.newCall(request).execute()</span><br><span class="line">                <span class="keyword">val</span> json = response.body?.string()</span><br><span class="line">                <span class="keyword">val</span> result = gson.fromJson&lt;T&gt;(json, genericReturnType)</span><br><span class="line"></span><br><span class="line">                <span class="comment">// 传出结果</span></span><br><span class="line">                emit(result)</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> -&gt; &#123;</span><br><span class="line">            <span class="keyword">val</span> response = okHttpClient.newCall(request).execute()</span><br><span class="line"></span><br><span class="line">            <span class="keyword">val</span> genericReturnType = method.genericReturnType</span><br><span class="line">            <span class="keyword">val</span> json = response.body?.string()</span><br><span class="line">            gson.fromJson&lt;Any?&gt;(json, genericReturnType)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 判断返回值类型是不是 Flow&lt;T&gt;</span></span><br><span class="line"><span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">isFlowReturn</span><span class="params">(method: <span class="type">Method</span>)</span></span> =</span><br><span class="line">        getRawType(method.genericReturnType) == Flow::<span class="keyword">class</span>.java</span><br></pre></td></tr></table></figure>

<p>由于代码段 13 当中已经有了 if、else 两个条件分支了，再增加一个分支的话，我们选择了 when 表达式。这里，我们增加了一个 isFlowReturn(method) 的分支，意思就是判断返回值类型是不是 Flow，如果是的话，我们就直接使用 flow{} 创建一个 Flow 返回了。</p>
<p>至此，我们 6.0 版本的开发工作，其实就已经完成了。是不是觉得非常轻松？<strong>对比起 Callback 转 Flow，让 KtHttp 直接支持 Flow 确实要简单很多</strong>。从这一点上，我们也可以看到 Flow 的强大和易用性。</p>
<p>那么在这时候，我们就可以写一些简单的测试代码，来验证我们的代码是否可靠了。</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段15</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="type">&lt;T : Any&gt;</span> <span class="title">invoke</span><span class="params">(path: <span class="type">String</span>, method: <span class="type">Method</span>, args: <span class="type">Array</span>&lt;<span class="type">Any</span>&gt;)</span></span>: Any? &#123;</span><br><span class="line">    <span class="comment">// 省略部分代码</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">when</span> &#123;</span><br><span class="line">        isKtCallReturn(method) -&gt; &#123;</span><br><span class="line">            <span class="keyword">val</span> genericReturnType = getTypeArgument(method)</span><br><span class="line">            KtCall&lt;T&gt;(call, gson, genericReturnType)</span><br><span class="line">        &#125;</span><br><span class="line">        isFlowReturn(method) -&gt; &#123;</span><br><span class="line">            <span class="comment">// 增加日志</span></span><br><span class="line">            logX(<span class="string">&quot;Start out&quot;</span>)</span><br><span class="line">            flow&lt;T&gt; &#123;</span><br><span class="line">                logX(<span class="string">&quot;Start in&quot;</span>)</span><br><span class="line">                <span class="keyword">val</span> genericReturnType = getTypeArgument(method)</span><br><span class="line">                <span class="keyword">val</span> response = okHttpClient.newCall(request).execute()</span><br><span class="line">                <span class="keyword">val</span> json = response.body?.string()</span><br><span class="line">                <span class="keyword">val</span> result = gson.fromJson&lt;T&gt;(json, genericReturnType)</span><br><span class="line">                logX(<span class="string">&quot;Start emit&quot;</span>)</span><br><span class="line">                emit(result)</span><br><span class="line">                logX(<span class="string">&quot;End emit&quot;</span>)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> -&gt; &#123;</span><br><span class="line">            <span class="keyword">val</span> response = okHttpClient.newCall(request).execute()</span><br><span class="line"></span><br><span class="line">            <span class="keyword">val</span> genericReturnType = method.genericReturnType</span><br><span class="line">            <span class="keyword">val</span> json = response.body?.string()</span><br><span class="line">            gson.fromJson&lt;Any?&gt;(json, genericReturnType)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">testFlow</span><span class="params">()</span></span> =</span><br><span class="line">    KtHttpV5.create(ApiServiceV5::<span class="keyword">class</span>.java)</span><br><span class="line">        .reposFlow(lang = <span class="string">&quot;Kotlin&quot;</span>, since = <span class="string">&quot;weekly&quot;</span>)</span><br><span class="line">        .flowOn(Dispatchers.IO) <span class="comment">//切换线程</span></span><br><span class="line">        .<span class="keyword">catch</span> &#123; println(<span class="string">&quot;Catch: <span class="variable">$it</span>&quot;</span>) &#125;</span><br><span class="line">        .collect &#123;</span><br><span class="line">            logX(<span class="string">&quot;<span class="subst">$&#123;it.count&#125;</span>&quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Start out</span></span><br><span class="line"><span class="comment">Thread:main @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Start in</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#2</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Start emit</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#2</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">End emit</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#2</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">25</span></span><br><span class="line"><span class="comment">Thread:main @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">程序结束</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>在上面的代码中，我们增加了一些日志，同时在调用处增加了“flowOn(Dispatchers.IO)”。可以看到，这样一来整个网络请求就执行在了 DefaultDispatcher 这个线程池当中，而其他部分的代码，仍然执行在 main() 线程。这也是符合预期的。</p>
<p>然后，我们可以通过断网来模拟出现异常的情况：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段16</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">输出结果：</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Start out</span></span><br><span class="line"><span class="comment">Thread:main @coroutine#1</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Start in</span></span><br><span class="line"><span class="comment">Thread:DefaultDispatcher-worker-1 @coroutine#2</span></span><br><span class="line"><span class="comment">================================</span></span><br><span class="line"><span class="comment">Catch: java.net.UnknownHostException:  nodename nor servname provided, or not known</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">程序结束</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>可以看到，程序的运行结果仍然是符合预期的。</p>
<p>下面，我们再来看看 6.0 完整的代码：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段17</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> <span class="title class_">ApiServiceV5</span> &#123;</span><br><span class="line">    <span class="meta">@GET(<span class="string">&quot;/repo&quot;</span>)</span></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">repos</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">        <span class="meta">@Field(<span class="string">&quot;lang&quot;</span>)</span> lang: <span class="type">String</span>,</span></span></span><br><span class="line"><span class="params"><span class="function">        <span class="meta">@Field(<span class="string">&quot;since&quot;</span>)</span> since: <span class="type">String</span></span></span></span><br><span class="line"><span class="params"><span class="function">    )</span></span>: KtCall&lt;RepoList&gt;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 注释1</span></span><br><span class="line">    <span class="meta">@GET(<span class="string">&quot;/repo&quot;</span>)</span></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">reposFlow</span><span class="params">(</span></span></span><br><span class="line"><span class="params"><span class="function">        <span class="meta">@Field(<span class="string">&quot;lang&quot;</span>)</span> lang: <span class="type">String</span>,</span></span></span><br><span class="line"><span class="params"><span class="function">        <span class="meta">@Field(<span class="string">&quot;since&quot;</span>)</span> since: <span class="type">String</span></span></span></span><br><span class="line"><span class="params"><span class="function">    )</span></span>: Flow&lt;RepoList&gt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">object</span> KtHttpV5 &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">var</span> okHttpClient: OkHttpClient = OkHttpClient()</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">var</span> gson: Gson = Gson()</span><br><span class="line">    <span class="keyword">var</span> baseUrl = <span class="string">&quot;https://baseUrl.com&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="type">&lt;T : Any&gt;</span> <span class="title">create</span><span class="params">(service: <span class="type">Class</span>&lt;<span class="type">T</span>&gt;)</span></span>: T &#123;</span><br><span class="line">        <span class="keyword">return</span> Proxy.newProxyInstance(</span><br><span class="line">            service.classLoader,</span><br><span class="line">            arrayOf&lt;Class&lt;*&gt;&gt;(service)</span><br><span class="line">        ) &#123; proxy, method, args -&gt;</span><br><span class="line">            <span class="keyword">val</span> annotations = method.annotations</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">annotation</span> <span class="keyword">in</span> annotations) &#123;</span><br><span class="line">                <span class="keyword">if</span> (<span class="keyword">annotation</span> <span class="keyword">is</span> GET) &#123;</span><br><span class="line">                    <span class="keyword">val</span> url = baseUrl + <span class="keyword">annotation</span>.value</span><br><span class="line">                    <span class="keyword">return</span><span class="symbol">@newProxyInstance</span> invoke&lt;T&gt;(url, method, args!!)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span><span class="symbol">@newProxyInstance</span> <span class="literal">null</span></span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">as</span> T</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="type">&lt;T : Any&gt;</span> <span class="title">invoke</span><span class="params">(path: <span class="type">String</span>, method: <span class="type">Method</span>, args: <span class="type">Array</span>&lt;<span class="type">Any</span>&gt;)</span></span>: Any? &#123;</span><br><span class="line">        <span class="keyword">if</span> (method.parameterAnnotations.size != args.size) <span class="keyword">return</span> <span class="literal">null</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">var</span> url = path</span><br><span class="line">        <span class="keyword">val</span> parameterAnnotations = method.parameterAnnotations</span><br><span class="line">        <span class="keyword">for</span> (i <span class="keyword">in</span> parameterAnnotations.indices) &#123;</span><br><span class="line">            <span class="keyword">for</span> (parameterAnnotation <span class="keyword">in</span> parameterAnnotations[i]) &#123;</span><br><span class="line">                <span class="keyword">if</span> (parameterAnnotation <span class="keyword">is</span> Field) &#123;</span><br><span class="line">                    <span class="keyword">val</span> key = parameterAnnotation.value</span><br><span class="line">                    <span class="keyword">val</span> value = args[i].toString()</span><br><span class="line">                    <span class="keyword">if</span> (!url.contains(<span class="string">&quot;?&quot;</span>)) &#123;</span><br><span class="line">                        url += <span class="string">&quot;?<span class="variable">$key</span>=<span class="variable">$value</span>&quot;</span></span><br><span class="line">                    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                        url += <span class="string">&quot;&amp;<span class="variable">$key</span>=<span class="variable">$value</span>&quot;</span></span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">val</span> request = Request.Builder()</span><br><span class="line">            .url(url)</span><br><span class="line">            .build()</span><br><span class="line"></span><br><span class="line">        <span class="keyword">val</span> call = okHttpClient.newCall(request)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">when</span> &#123;</span><br><span class="line">            isKtCallReturn(method) -&gt; &#123;</span><br><span class="line">                <span class="keyword">val</span> genericReturnType = getTypeArgument(method)</span><br><span class="line">                KtCall&lt;T&gt;(call, gson, genericReturnType)</span><br><span class="line">            &#125;</span><br><span class="line">            isFlowReturn(method) -&gt; &#123;</span><br><span class="line">                logX(<span class="string">&quot;Start out&quot;</span>)</span><br><span class="line"></span><br><span class="line">                <span class="comment">// 注释2</span></span><br><span class="line">                flow&lt;T&gt; &#123;</span><br><span class="line">                    logX(<span class="string">&quot;Start in&quot;</span>)</span><br><span class="line">                    <span class="keyword">val</span> genericReturnType = getTypeArgument(method)</span><br><span class="line">                    <span class="keyword">val</span> response = okHttpClient.newCall(request).execute()</span><br><span class="line">                    <span class="keyword">val</span> json = response.body?.string()</span><br><span class="line">                    <span class="keyword">val</span> result = gson.fromJson&lt;T&gt;(json, genericReturnType)</span><br><span class="line">                    logX(<span class="string">&quot;Start emit&quot;</span>)</span><br><span class="line">                    emit(result)</span><br><span class="line">                    logX(<span class="string">&quot;End emit&quot;</span>)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> -&gt; &#123;</span><br><span class="line">                <span class="keyword">val</span> response = okHttpClient.newCall(request).execute()</span><br><span class="line"></span><br><span class="line">                <span class="keyword">val</span> genericReturnType = method.genericReturnType</span><br><span class="line">                <span class="keyword">val</span> json = response.body?.string()</span><br><span class="line">                gson.fromJson&lt;Any?&gt;(json, genericReturnType)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">getTypeArgument</span><span class="params">(method: <span class="type">Method</span>)</span></span> =</span><br><span class="line">        (method.genericReturnType <span class="keyword">as</span> ParameterizedType).actualTypeArguments[<span class="number">0</span>]</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">isKtCallReturn</span><span class="params">(method: <span class="type">Method</span>)</span></span> =</span><br><span class="line">        getRawType(method.genericReturnType) == KtCall::<span class="keyword">class</span>.java</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">isFlowReturn</span><span class="params">(method: <span class="type">Method</span>)</span></span> =</span><br><span class="line">        getRawType(method.genericReturnType) == Flow::<span class="keyword">class</span>.java</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> = runBlocking &#123;</span><br><span class="line">    testFlow()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">suspend</span> <span class="function"><span class="keyword">fun</span> <span class="title">testFlow</span><span class="params">()</span></span> =</span><br><span class="line">    KtHttpV5.create(ApiServiceV5::<span class="keyword">class</span>.java)</span><br><span class="line">        .reposFlow(lang = <span class="string">&quot;Kotlin&quot;</span>, since = <span class="string">&quot;weekly&quot;</span>)</span><br><span class="line">        .flowOn(Dispatchers.IO)</span><br><span class="line">        .<span class="keyword">catch</span> &#123; println(<span class="string">&quot;Catch: <span class="variable">$it</span>&quot;</span>) &#125;</span><br><span class="line">        .collect &#123;</span><br><span class="line">            logX(<span class="string">&quot;<span class="subst">$&#123;it.count&#125;</span>&quot;</span>)</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>

<p>最后，我们也再来分析一下，为什么 6.0 的代码可以这么简单。这里有两个关键的地方，我也分别用注释标记了。</p>
<p>请你留意注释 1 处的 <strong>reposFlow()</strong> 方法的定义，它其实是一个普通的函数，并不是挂起函数。换言之，虽然它的返回值类型是 Flow，但我们并不要求它在协程当中被调用。</p>
<p>另外，请留意注释 2 处<strong>，flow{}</strong> 这个高阶函数，它也只是一个普通函数，同样也不是挂起函数，这就意味着，它可以在普通函数里面直接调用。我们可以看看 flow{} 的定义：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段18</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 不是挂起函数</span></span><br><span class="line"><span class="keyword">public</span> <span class="function"><span class="keyword">fun</span> <span class="type">&lt;T&gt;</span> <span class="title">flow</span><span class="params">(<span class="meta">@BuilderInference</span> block: <span class="type">suspend</span> <span class="type">FlowCollector</span>&lt;<span class="type">T</span>&gt;.() -&gt; <span class="type">Unit</span>)</span></span>: Flow&lt;T&gt; = SafeFlow(block)</span><br></pre></td></tr></table></figure>

<p>所以，正因为以上这两点，就使得 Flow 的易用性非常高，还记得我们在第 20 讲当中看过的那张 Flow“上游、下游”的示意图吗？我们其实可以进一步完善它：</p>
<p><img src= "https://s2.loli.net/2023/03/09/dog2qQY83iTIvHM.gif" data-lazy-src="https://static001.geekbang.org/resource/image/37/20/370553ac768913a0702fda89a85b8120.jpg?wh=2000x1125" alt="img"></p>
<p>也就是说，对于 Flow 的<strong>上游、中间操作符</strong>而言，它们其实根本就不需要协程作用域，只有在下游调用 collect{} 的时候，才需要协程作用域。</p>
<p>因此，我们前面在写 main() 函数的时候，也可以换成这样的写法：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段19</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="comment">// 协程作用域外</span></span><br><span class="line">    <span class="keyword">val</span> flow = KtHttpV5.create(ApiServiceV5::<span class="keyword">class</span>.java)</span><br><span class="line">        .reposFlow(lang = <span class="string">&quot;Kotlin&quot;</span>, since = <span class="string">&quot;weekly&quot;</span>)</span><br><span class="line">        .flowOn(Dispatchers.IO)</span><br><span class="line">        .<span class="keyword">catch</span> &#123; println(<span class="string">&quot;Catch: <span class="variable">$it</span>&quot;</span>) &#125;</span><br><span class="line"></span><br><span class="line">    runBlocking &#123;</span><br><span class="line">        <span class="comment">// 协程作用域内</span></span><br><span class="line">        flow.collect &#123;</span><br><span class="line">            logX(<span class="string">&quot;<span class="subst">$&#123;it.count&#125;</span>&quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可见，正因为 Flow 的上游不需要协程作用域，我们才可以轻松完成 6.0 版本的代码。</p>
<h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h2><p>这节实战课，为了让 KtHttp 支持 Flow API，我们使用了两种方法。第一种，是从 KtHttp 的外部进行扩展，用这种思路，我们完成了 5.0 版本的开发；第二种，是修改 KtHttp 的内部，让 ApiService 当中的方法可以直接以 Flow 作为返回值类型，利用这种思路，我们完成了 6.0 的开发。</p>
<p>具体来说，我们是用到了这几个知识点，你可以重点关注一下：</p>
<ul>
<li>**callbackFlow{}**，它的作用就是把 Callback 转换成 Flow。它的底层其实用到了 Channel，因此，我们可以在 callbackFlow{} 当中调用 trySend()、trySendBlocking()，这两个方法都是 Channel 当中的“非挂起函数”的方法。需要注意的是，这里我们不能直接使用 Channel 的挂起函数 send()，因为它必须要在协程体当中执行。</li>
<li>在 callbackFlow{} 里，出现异常的逻辑分支当中，如果我们需要关闭 callbackFlow，那么在调用 close() 的时候，一定要传入对应的异常参数 **close(throwable)**。不然的话，Flow 的下游就无法收到任何的异常信息。</li>
<li>在 callbackFlow{} 当中创建的<strong>协程任务</strong>，也可以跟随 callbackFlow 一同被取消，只要我们不打破它原有的协程父子关系。</li>
<li>由于 <strong>Flow 的上游、中间操作符</strong>不需要协程作用域，因此，我们可以在非协程当中执行创建 Flow。这就导致我们 6.0 版本的代码轻松就可以实现。</li>
</ul>
<h2 id="思考题"><a href="#思考题" class="headerlink" title="思考题"></a>思考题</h2><p>在 5.0 版本的代码中，awaitClose{} 的作用是响应协程的取消，同时取消 OkHttp 的请求。其实，它除了这个作用以外，还有另外一个作用。</p>
<p>你可以把 5.0 版本代码中的 awaitClose 删掉，看看会发生什么。对于这样的现象，你能想到 awaitClose{} 的另一个作用吗？</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 代码段20</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="type">&lt;T : Any&gt;</span> KtCall<span class="type">&lt;T&gt;</span>.<span class="title">asFlow</span><span class="params">()</span></span>: Flow&lt;T&gt; = callbackFlow &#123;</span><br><span class="line">    <span class="keyword">val</span> call = call(<span class="keyword">object</span> : Callback&lt;T&gt; &#123;</span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onSuccess</span><span class="params">(<span class="keyword">data</span>: <span class="type">T</span>)</span></span> &#123;</span><br><span class="line">            trySendBlocking(<span class="keyword">data</span>)</span><br><span class="line">                .onSuccess &#123; close() &#125;</span><br><span class="line">                .onFailure &#123;</span><br><span class="line">                    cancel(CancellationException(<span class="string">&quot;Send channel fail!&quot;</span>, it))</span><br><span class="line">                &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onFail</span><span class="params">(throwable: <span class="type">Throwable</span>)</span></span> &#123;</span><br><span class="line">            cancel(CancellationException(<span class="string">&quot;Request fail!&quot;</span>, throwable))</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 注意这里</span></span><br><span class="line">    <span class="comment">// awaitClose &#123;</span></span><br><span class="line">    <span class="comment">//     call.cancel()</span></span><br><span class="line">    <span class="comment">// &#125;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://devsu.top">Carl Su</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://devsu.top/posts/6532289/">https://devsu.top/posts/6532289/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://devsu.top" target="_blank">码行</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Kotlin/">Kotlin</a></div><div class="post_share"><div class="social-share" data-image="http://t15.baidu.com/it/u=1016075162,2061563941&amp;fm=224&amp;app=112&amp;f=JPEG?w=354&amp;h=500" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/85d82fa8/" title="Kotlin编程第一课--(答疑篇)答疑（一）| Java和Kotlin到底谁好谁坏？"><img class="cover" src="https://img0.baidu.com/it/u=1043079064,1717028606&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=800&amp;h=500" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Kotlin编程第一课--(答疑篇)答疑（一）| Java和Kotlin到底谁好谁坏？</div></div></a></div><div class="next-post pull-right"><a href="/posts/a3460e51/" title="Kotlin编程第一课--(协程篇)23  异常：try-catch 坑！"><img class="cover" src="http://t15.baidu.com/it/u=2335792902,1551903918&amp;fm=224&amp;app=112&amp;f=JPEG?w=500&amp;h=445" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Kotlin编程第一课--(协程篇)23  异常：try-catch 坑！</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/85d82fa8/" title="Kotlin编程第一课--(基础篇)06  扩展：你的能力边界到底在哪里？"><img class="cover" src="https://static001.geekbang.org/resource/image/b6/1c/b65feyy0bdc4764c6564a95912d7851c.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-05-06</div><div class="title">Kotlin编程第一课--(基础篇)06  扩展：你的能力边界到底在哪里？</div></div></a></div><div><a href="/posts/be9f17d6/" title="Kotlin编程第一课(目录)"><img class="cover" src="https://img2.baidu.com/it/u=3956021957,3313212296&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-10</div><div class="title">Kotlin编程第一课(目录)</div></div></a></div><div><a href="/posts/83a7144c/" title="2023-01-17-Kotlin协程 -  结构化并发"><img class="cover" src="https://s2.loli.net/2023/03/14/xEyFgn24zZPXe15.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-17</div><div class="title">2023-01-17-Kotlin协程 -  结构化并发</div></div></a></div><div><a href="/posts/68bf7d20/" title="Kotlin函数"><img class="cover" src="https://img1.baidu.com/it/u=1546227440,2897989905&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Kotlin函数</div></div></a></div><div><a href="/posts/a20c9e06/" title="Kotlin协程"><img class="cover" src="https://s2.loli.net/2023/03/14/3MHPBy1Q4GncRlF.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-09</div><div class="title">Kotlin协程</div></div></a></div><div><a href="/posts/8c331668/" title="Kotlin内置函数apply、let、run、with、also等区别"><img class="cover" src="https://s2.loli.net/2023/03/14/OpxWcuy2ktMzoQD.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Kotlin内置函数apply、let、run、with、also等区别</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div><div id="comment-switch"><span class="first-comment">Valine</span><span class="switch-btn"></span><span class="second-comment">Disqus</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div><div><div id="disqus_thread"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Kotlin%E7%BC%96%E7%A8%8B%E7%AC%AC%E4%B8%80%E8%AF%BE%E2%80%93-%E5%8D%8F%E7%A8%8B%E7%AF%87-24-%E5%AE%9E%E6%88%98%EF%BC%9A%E8%AE%A9KtHttp%E6%94%AF%E6%8C%81Flow"><span class="toc-number">1.</span> <span class="toc-text">Kotlin编程第一课–(协程篇)24 | 实战：让KtHttp支持Flow</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#5-0-%E7%89%88%E6%9C%AC%EF%BC%9ACallback-%E8%BD%AC-Flow"><span class="toc-number">1.1.</span> <span class="toc-text">5.0 版本：Callback 转 Flow</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-0-%E7%89%88%E6%9C%AC%EF%BC%9A%E7%9B%B4%E6%8E%A5%E6%94%AF%E6%8C%81-Flow"><span class="toc-number">1.2.</span> <span class="toc-text">6.0 版本：直接支持 Flow</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B0%8F%E7%BB%93"><span class="toc-number">1.3.</span> <span class="toc-text">小结</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%9D%E8%80%83%E9%A2%98"><span class="toc-number">1.4.</span> <span class="toc-text">思考题</span></a></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2018 - 2023 By Carl Su</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">学无止境</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: '',
      appKey: '',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script><script>function loadDisqus () {
  var disqus_config = function () {
    this.page.url = 'https://devsu.top/posts/6532289/'
    this.page.identifier = '/posts/6532289/'
    this.page.title = 'Kotlin编程第一课--(协程篇)24  实战：让KtHttp支持Flow'
  };

  window.disqusReset = () => {
    DISQUS.reset({
      reload: true,
      config: disqus_config
    })
  }

  if (window.DISQUS) disqusReset()
  else {
    (function() { 
      var d = document, s = d.createElement('script');
      s.src = 'https://.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
    })();
  }

  document.getElementById('darkmode').addEventListener('click', () => {
    setTimeout(() => window.disqusReset(), 200)
  })
}

if ('Valine' === 'Disqus' || !true) {
  if (true) btf.loadComment(document.getElementById('disqus_thread'), loadDisqus)
  else loadDisqus()
} else {
  function loadOtherComment () {
    loadDisqus()
  }
}
</script></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>